package com.example.onlinemonitoring.WebSocket;

import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class TestWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final Logger logger = LogManager.getLogger(TestWebSocketHandler.class);
    /**
     * 存储已经登录用户的channel对象
     */
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 存储用户id和用户的channelId绑定
     */
    public static ConcurrentHashMap<Integer, ChannelId> userMap = new ConcurrentHashMap<>();
    /**
     * 用于存储群聊房间号和群聊成员的channel信息
     */
    public static ConcurrentHashMap<String, Channel> groupMap = new ConcurrentHashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("与客户端建立连接，通道开启！");
        ctx.channel().writeAndFlush(new TextWebSocketFrame("message"));
        // 添加到channelGroup通道组
        channelGroup.add(ctx.channel());
        ctx.channel().id();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("与客户端断开连接，通道关闭！");
        // 添加到channelGroup 通道组
        channelGroup.remove(ctx.channel());
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            String name = getUrlParams(uri);
            groupMap.put(name, ctx.channel());
            logger.info("连接的设备简称是：{}", name);
            // if (uri.contains("?")) {
            // String newUri = uri.substring(0, uri.indexOf("?"));
            // request.setUri(newUri);
            // }
            request.setUri("/ws");
        }
        super.channelRead(ctx, msg);
    }

    public static void sendAllMessage(String message, String name) {
        if (groupMap.get(name) != null)
            groupMap.get(name).writeAndFlush(new TextWebSocketFrame(message));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame)
            throws Exception {
    }

    private static String getUrlParams(String url) {
        if (!url.contains("=")) {
            return null;
        }
        String name = url.substring(url.indexOf("=") + 1);
        return name;
    }
}